/* 通过 rollup 打包 */

// const path = require('path');
// const json = require('@rollup/plugin-json');
// const ts = require('rollup-plugin-typescript2');
// const resolvePlugin = require('@rollup/plugin-node-resolve');
import path from 'path';
import json from '@rollup/plugin-json';
import ts from 'rollup-plugin-typescript2';
import resolvePlugin from '@rollup/plugin-node-resolve';

// 获取需要打包的文件路径
const packagesDir = path.resolve('packages');
console.log("packagesDir------------------", packagesDir);
let packageDir = path.resolve(packagesDir, process.env.TARGET);


// 拿到每个对应的包的配置
const resolve = p => path.resolve(packageDir, p);
const pkg = require(resolve(`package.json`)); // 拿到当前包的配置
let buildOptions = pkg.buildOptions || []; // 拿到当前包的自定义配置



console.log("pkg", pkg);
console.log("buildOptions", buildOptions);
console.log("packagesDir", packagesDir);
console.log("packageDir", packageDir);


// 创建一个表
const outputConfigs = {
  "esm-bundler": {
    file: resolve(`dist/${pkg.name}.esm-bundler.js`),
    format: `es`
  },
  "esm-browser": {
    file: resolve(`dist/${pkg.name}.esm-browser.js`),
    format: `es`
  },
  "cjs": {
    file: resolve(`dist/${pkg.name}.cjs.js`),
    format: `cjs`
  },
  "global": {
    file: resolve(`dist/${pkg.name}.global.js`),
    format: `iife`
  }
};


function createConfig(format, output) {
  // 进行打包
  output.name = buildOptions.name; // 获取名字
  output.sourcemap = true // 打包时生成 sourcemap 文件

  // 生成 rollup 的配置
  return {
    input: resolve(`src/index.ts`), // 入口文件
    plugins: [
      json(),
      ts({
        tsconfig: path.resolve(__dirname, 'tsconfig.json')
      }),
      resolvePlugin()
    ],
    output
  }

}

// 需要导出一个配置
export default buildOptions.formats.map(format => createConfig(format, outputConfigs[format]));

